package site.kitcheng.springboottest.app.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import site.kitcheng.springboottest.api.controller.dto.UserDto;
import site.kitcheng.springboottest.app.service.ISysProfileService;
import site.kitcheng.springboottest.app.service.ISysUserService;
import site.kitcheng.springboottest.domain.CustomUserDetails;
import site.kitcheng.springboottest.domain.SysUser;
import site.kitcheng.springboottest.infra.constant.BaseConstant;
import site.kitcheng.springboottest.infra.manager.AsyncManager;
import site.kitcheng.springboottest.infra.mapper.SysUserMapper;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Autowired
    ISysProfileService sysProfileService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser>  sysUserQuery = new LambdaQueryWrapper<>();
        SysUser sysUser = baseMapper.selectOne(sysUserQuery.eq(SysUser::getUserName, username));
        return new CustomUserDetails(sysUser);
    }

    @Override
    public String login(UserDto userDto) {
        validateCaptcha(userDto.getUserName(), userDto.getCode(), userDto.getUuid());

        return "";
    }


    public void validateCaptcha(String username, String code, String uuid)
    {

        String profileCode = sysProfileService.getProfileCode("user.login.code", null, null);
        boolean captchaEnabled = BooleanUtil.toBoolean(profileCode);

        if (captchaEnabled) {
            String verifyKey =  BaseConstant.CAPTCHA_CODE_KEY + uuid.trim();
            String captcha =stringRedisTemplate.opsForValue().get(verifyKey);
            if (captcha == null)
            {
//                AsyncManager.asyn().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
//                throw new CaptchaExpireException();
            }
            stringRedisTemplate.delete(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
//                AsyncManager.asyn().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//                throw new CaptchaException();
            }
        }
    }


}
